﻿namespace StockSharp.Algo.Indicators.Trend
{
	using System;

	using StockSharp.Algo.Candles;
	using StockSharp.BusinessEntities;

	/// <summary>
	/// ВпадинаБар.
	/// </summary>
	/// <remarks>
	/// http://www2.wealth-lab.com/WL5Wiki/TroughBar.ashx
	/// </remarks>
	public class TroughBar : BaseIndicator<decimal>
	{
		private decimal _currentMinimum = decimal.MaxValue;
		private int _currentBarCount;
		private int _valueBarCount;

		/// <summary>
		/// Создать <see cref="TroughBar"/>.
		/// </summary>
		public TroughBar()
			: base(typeof(Candle))
		{
		}

		private Unit _reversalAmount = new Unit();

		/// <summary>
		/// Порог изменения индикатора.
		/// </summary>
		public Unit ReversalAmount
		{
			get { return _reversalAmount; }
			set
			{
				if (value == null)
					throw new ArgumentNullException("value");

				_reversalAmount = value;

				Reset();
			}
		}

		/// <summary>
		/// Обработать входное значение.
		/// </summary>
		/// <param name="input">Входное значение.</param>
		/// <returns>Результирующее значение.</returns>
		protected override decimal OnProcess(IIndicatorValue input)
		{
			var candle = input.GetValue<Candle>();

			try
			{
				if (candle.LowPrice < _currentMinimum)
				{
					_currentMinimum = candle.LowPrice;
					_valueBarCount = _currentBarCount;
				}
				else if (candle.HighPrice >= _currentMinimum + ReversalAmount.Value)
				{
					IsFormed = true;
					return _valueBarCount;
				}

				return this.GetCurrentValue();
			}
			finally
			{
				_currentBarCount++;
			}
		}
	}
}